


from flask import Blueprint, request, jsonify, g

from db_utils.postgresql_connection import PostgreSQLConnection
from db_utils.repositories.video_resources_table import VideoResourcesTable
from push_device_task import PushDeviceTask

import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

video_resources_blueprint = Blueprint('video_resources_blueprint', __name__)

@video_resources_blueprint.route('/create_video_resources', methods=['POST'])
def create_video_resources():
    
    data_json = request.form.get('data_json')

    if not data_json:
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})

    with PostgreSQLConnection() as (conn, cursor):
        try:
            video_resources_table = VideoResourcesTable(conn, cursor)
            status, result = video_resources_table.create_video_resources(data_json)

        except Exception as e:
            logger.error("Error creating video resources: {}".format(e))
            return jsonify({"status": -1, "errorCode": 1002, "errorMsg": str(e), "resultBody": None})

        else:
            if status:
                return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": {"id": result}})
            else:
                return jsonify({"status": -1, "errorCode": 1003, "errorMsg": result, "resultBody": None})

@video_resources_blueprint.route('/get_video_resources_by_id', methods=['GET'])
def get_video_resources_by_id():
    
    vs_id = request.args.get('vs_id')

    if not vs_id:
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})

    with PostgreSQLConnection() as (conn, cursor):
        try:
            video_resources_table = VideoResourcesTable(conn, cursor)
            video_resources = video_resources_table.get_video_resources_by_id(vs_id)

        except Exception as e:
            logger.error("Error getting video resources by id: {}".format(e))
            return jsonify({"status": -1, "errorCode": 1002, "errorMsg": str(e), "resultBody": None})

        else:
            if video_resources:
                return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": video_resources})
            else:
                return jsonify({"status": -1, "errorCode": 1003, "errorMsg": "视频配置不存在", "resultBody": None})

@video_resources_blueprint.route('/get_latest_video_resources', methods=['GET']) # 获取最新视频配置
def get_latest_video_resources():
    
    with PostgreSQLConnection() as (conn, cursor):
        try:
            video_resources_table = VideoResourcesTable(conn, cursor)
            video_resources = video_resources_table.get_latest_video_resources()

        except Exception as e:
            logger.error("Error getting latest video resources: {}".format(e))
            return jsonify({"status": -1, "errorCode": 1002, "errorMsg": str(e), "resultBody": None})

        else:
            if video_resources:
                return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": video_resources})
            else:
                return jsonify({"status": -1, "errorCode": 1003, "errorMsg": "没有最新视频配置", "resultBody": None})

@video_resources_blueprint.route('/get_all_video_resources', methods=['GET']) # 获取所有视频配置
def get_all_video_resources():
    
    offset = request.args.get('offset', default=0, type=int)
    limit = request.args.get('limit', default=10, type=int)

    with PostgreSQLConnection() as (conn, cursor):
        try:
            video_resources_table = VideoResourcesTable(conn, cursor)
            status,video_resources = video_resources_table.get_all_video_resources(offset, limit)

        except Exception as e:
            logger.error("Error getting all video resources: {}".format(e))
            return jsonify({"status": -1, "errorCode": 1002, "errorMsg": str(e), "resultBody": None})

        else:
            if status:
                return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": video_resources})
            else:
                return jsonify({"status": -1, "errorCode": 1003, "errorMsg": str(video_resources), "resultBody": None})

@video_resources_blueprint.route('/delete_video_resources', methods=['POST']) # 删除视频配置
def delete_video_resources():
    
    vs_id = request.form.get('vs_id')

    if not vs_id:
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})

    with PostgreSQLConnection() as (conn, cursor):
        try:
            video_resources_table = VideoResourcesTable(conn, cursor)
            status, result = video_resources_table.delete_video_resources(vs_id)

        except Exception as e:
            logger.error("Error deleting video resources: {}".format(e))
            return jsonify({"status": -1, "errorCode": 1002, "errorMsg": str(e), "resultBody": None})

        else:
            if status:
                return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": None})
            else:
                return jsonify({"status": -1, "errorCode": 1003, "errorMsg": result, "resultBody": None})

@video_resources_blueprint.route('/create_video_resources_device_relation', methods=['POST']) # 创建设备和视频配置关联
def create_video_resources_device_relation():
    
    device_id = request.form.get('device_id')
    video_resources_id = request.form.get('video_resources_id')

    if not device_id or not video_resources_id:
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})

    with PostgreSQLConnection() as (conn, cursor):
        try:
            video_resources_table = VideoResourcesTable(conn, cursor)
            status, result = video_resources_table.create_video_resources_device_relation(device_id, video_resources_id)

        except Exception as e:
            logger.error("Error creating video resources device relation: {}".format(e))
            return jsonify({"status": -1, "errorCode": 1002, "errorMsg": str(e), "resultBody": None})

        else:
            if not status:

                return jsonify({"status": -1, "errorCode": 1003, "errorMsg": result, "resultBody": None})
            
            else:

                # 给设备下发配置信息
                status, error_msg = PushDeviceTask().send_health_video_message_to_redis_by_id(device_id, video_resources_id)

                if not status:

                    return jsonify({"status": -1, "errorCode": 1004, "errorMsg": error_msg, "resultBody": None})
                
                return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": None})
            

@video_resources_blueprint.route('/get_video_resources_by_device_id', methods=['GET']) # 根据设备id获取视频配置
def get_video_resources_by_device_id():
    
    device_id = request.args.get('device_id')

    if not device_id:
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})

    with PostgreSQLConnection() as (conn, cursor):
        try:
            video_resources_table = VideoResourcesTable(conn, cursor)
            status, video_resources_device = video_resources_table.get_video_resources_by_device_id(device_id)

        except Exception as e:  
            logger.error("Error getting video resources by device id: {}".format(e))
            return jsonify({"status": -1, "errorCode": 1002, "errorMsg": str(e), "resultBody": None})

        else:
            if status:
                return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": video_resources_device})
            else:
                return jsonify({"status": -1, "errorCode": 1003, "errorMsg": video_resources_device, "resultBody": None})
            
@video_resources_blueprint.route('/get_device_by_video_resources_id', methods=['GET']) # 根据视频配置id获取设备
def get_device_by_video_resources_id():
    
    video_resources_id = request.args.get('video_resources_id')

    if not video_resources_id:
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})

    with PostgreSQLConnection() as (conn, cursor):
        try:
            video_resources_table = VideoResourcesTable(conn, cursor)
            status, video_resources_device = video_resources_table.get_device_by_video_resources_id(video_resources_id)

        except Exception as e:  
            logger.error("Error getting device by video resources id: {}".format(e))
            return jsonify({"status": -1, "errorCode": 1002, "errorMsg": str(e), "resultBody": None})

        else:
            if status:
                return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": video_resources_device})
            else:
                return jsonify({"status": -1, "errorCode": 1003, "errorMsg": str(video_resources_device), "resultBody": None})

@video_resources_blueprint.route('/delete_video_resources_device_relation', methods=['POST']) # 删除设备和视频配置关联
def delete_video_resources_device_relation():
    
    device_id = request.form.get('device_id')
    video_resources_id = request.form.get('video_resources_id')

    if not device_id or not video_resources_id:
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})

    with PostgreSQLConnection() as (conn, cursor):
        try:
            video_resources_table = VideoResourcesTable(conn, cursor)
            status, result = video_resources_table.delete_video_resources_device_relation(device_id, video_resources_id)

        except Exception as e:
            logger.error("Error deleting video resources device relation: {}".format(e))
            return jsonify({"status": -1, "errorCode": 1002, "errorMsg": str(e), "resultBody": None})

        else:
            if status:
                return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": None})
            else:
                return jsonify({"status": -1, "errorCode": 1003, "errorMsg": result, "resultBody": None})
            



